package com.xiefengf.utils;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * @author xiefengf
 * @version 1.0
 * @date 2023/7/29 18:44
 */
public class RabbitUtils {

    /**
     * 声明队列
     * @param queueName
     */
    public static void queueDeclare(String exchange, BuiltinExchangeType exchangeType,String queueName,String routingKey){
        try {
            Connection conn = RabbitUtils.getConn();
            Channel channel = RabbitUtils.getChannel(conn);
            // 声明exchange中的消息为可持久化，不自动删除
            channel.exchangeDeclare(exchange, exchangeType, true, false, null);
            // 绑定队列到交换机 - 根据路由key绑定
            if (queueName != null){
                // 生成一个消息队列
                channel.queueDeclare(queueName,true,false,false,null);
            }else {
                // 不指定队列名称，会随机生成名称
                queueName = channel.queueDeclare("",true,false,false,null).getQueue();
            }
            channel.queueBind(queueName, exchange, routingKey);
            // 释放资源
            channel.close();
            conn.close();
        } catch (IOException | TimeoutException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 生产者
     *
     * @param exchange     交换器
     * @param toutingKey   路由键
     * @param message      发送的消息
     */
    public static void rabbitProducer(String exchange, String toutingKey, String message) {
        try {
            // 获取连接
            Connection conn = getConn();
            // 创建消息通道
            Channel channel = getChannel(conn);
            // 发布消息
            channel.basicPublish(exchange, toutingKey, null, message.getBytes());
            System.out.println("发布消息-》 '" + message + "'");
            // 释放资源
            channel.close();
            conn.close();
        } catch (IOException | TimeoutException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 消费者
     * @param queue 队列
     */
    public static void rabbitConsumer(String queue) {
        try {
            // 获取连接
            Connection conn = getConn();
            // 创建消息通道
            Channel channel = getChannel(conn);

            // 消费消息
            DefaultConsumer consumer = new DefaultConsumer(channel){
                // 重写方法
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    try {
                        // 解析消息
                        String message = new String(body, StandardCharsets.UTF_8);
                        // 处理消息
                        System.out.println(message);
                        // 回复成功Ack
                        channel.basicAck(envelope.getDeliveryTag(), false);
                    } catch (IOException e) {
                        // 回复失败Ack
                        channel.basicNack(envelope.getDeliveryTag(), false, true);
                    }
                }
            };
            // 取消自动ack --- 需要消费者确认后，生产者消息才会删除
            channel.basicConsume(queue, false, consumer);
        } catch (IOException | TimeoutException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 释放资源
     * @param channel
     * @param conn
     */
    public void close(Channel channel,Connection conn){
        // 释放资源
        try {
            channel.close();
            conn.close();
        } catch (IOException | TimeoutException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 获取信道
     *
     * @return
     */
    private static Channel getChannel(Connection connection) throws IOException, TimeoutException {
        return connection.createChannel();
    }

    /**
     * 创建连接
     *
     * @return
     */
    private static Connection getConn() throws IOException, TimeoutException {
        // 创建RabbitMQ的连接
        ConnectionFactory factory = new ConnectionFactory();
        // 配置工厂参数
        factory.setHost("124.220.215.81");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("xiefeng123");
        // 创建连接
        return factory.newConnection();
    }

}



